﻿using CommunityToolkit.Mvvm.Input;
using ICSharpCode.AvalonEdit;
using Newtonsoft.Json;
using NPinyin;
using Serilog;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Input;
using VideoTools.Extension;
using VideoTools.service;
using VideoTools.Util;
using VideoTools.vo;
using MessageBox = System.Windows.Forms.MessageBox;

namespace VideoTools.Commands
{
    public class TranslateSubtitleCommands : NotifyPropertyBase
    {
        private static volatile TranslateSubtitleCommands _instance;
        private static readonly object SyncRoot = new object();
        private static string Language_Original_Text = "原始语言:";
        private static string Language_Middle_Text = "中间语言:";

        private static int Option_Width = 130;
        public static TranslateSubtitleCommands Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new TranslateSubtitleCommands();
                        }
                    }
                }

                return _instance;
            }
        }

        private TranslateSubtitleCommands()
        {
            foreach (TranslateType dt in Utils.GetAllEnumValues<TranslateType>())
            {
                TypeOptions.Add(dt);
            }

            foreach (GoogleTranslateLanguage lang in Utils.getSortGoogleTranslateLanguages())
            {
                if (lang != GoogleTranslateLanguage.zh)
                {
                    string py = Pinyin.GetPinyin(lang.Desc());
                    string fl = py.Substring(0, 1).ToUpper();
                    GoogleTranslateLanguages.Add(lang);
                }
            }
            TranslateOptionsDisplyWidth = Option_Width;
            TranslateTimesDisplyWidth = Option_Width;
            LanguageDisplyWidth = 0;

            TranslateTimes = TranslateTimesList[0];

            TranslateLanguage = GoogleTranslateLanguages[0];
        }

        private int _TranslateTimesDisplyWidth = Option_Width;

        public int TranslateTimesDisplyWidth
        {
            get => _TranslateTimesDisplyWidth;
            set => SetProperty(ref _TranslateTimesDisplyWidth, value);
        }

        private int _LanguageDisplyWidth = Option_Width;

        public int LanguageDisplyWidth
        {
            get => _LanguageDisplyWidth;
            set => SetProperty(ref _LanguageDisplyWidth, value);
        }
        private int _TranslateOptionsDisplyWidth = Option_Width;

        public int TranslateOptionsDisplyWidth
        {
            get => _TranslateOptionsDisplyWidth;
            set => SetProperty(ref _TranslateOptionsDisplyWidth, value);
        }

        private string _LanguageText = Language_Original_Text;

        public string LanguageText
        {
            get => _LanguageText;
            set => SetProperty(ref _LanguageText, value);
        }

        private bool _SaveSubtitleEnabled = false;

        public bool SaveSubtitleEnabled
        {
            get => _SaveSubtitleEnabled;
            set => SetProperty(ref _SaveSubtitleEnabled, value);
        }
        private bool _TranslateSubtitleEnabled = false;

        public bool TranslateSubtitleEnabled
        {
            get => _TranslateSubtitleEnabled;
            set => SetProperty(ref _TranslateSubtitleEnabled, value);
        }
        private bool _MergeDisplay;

        public bool MergeDisplay
        {
            get => _MergeDisplay;
            set => SetProperty(ref _MergeDisplay, value);
        }
        private Visibility _SameToLastTranslateOptionVisibility = Visibility.Visible;

        public Visibility SameToLastTranslateOptionVisibility
        {
            get => _SameToLastTranslateOptionVisibility;
            set => SetProperty(ref _SameToLastTranslateOptionVisibility, value);
        }
        private GoogleTranslateLanguage _TranslateLanguage;
        public GoogleTranslateLanguage TranslateLanguage
        {
            get => _TranslateLanguage;
            set => SetProperty(ref _TranslateLanguage, value);
        }
        private TranslateType _TranslateType;
        public TranslateType TranslateType
        {
            get => _TranslateType;
            set => SetProperty(ref _TranslateType, value);
        }

        private ObservableCollection<TranslateType> _TypeOptions =
            new ObservableCollection<TranslateType>();

        public ObservableCollection<TranslateType> TypeOptions
        {
            get => _TypeOptions;
        }

        private ObservableCollection<int> _TranslateTimesList = new ObservableCollection<int>()
        {
            10,
            20,
            30,
            40,
            50,
            60,
            70,
            80,
            90,
        };

        public ObservableCollection<int> TranslateTimesList
        {
            get => _TranslateTimesList;
        }

        private ObservableCollection<GoogleTranslateLanguage> _GoogleTranslateLanguages =
            new ObservableCollection<GoogleTranslateLanguage>();

        public ObservableCollection<GoogleTranslateLanguage> GoogleTranslateLanguages
        {
            get => _GoogleTranslateLanguages;
        }

        private string _SubtitleFile1;

        public string SubtitleFile1
        {
            get => _SubtitleFile1;
            set => SetProperty(ref _SubtitleFile1, value);
        }
        private string _ActionLog;

        public string ActionLog
        {
            get => _ActionLog;
            set => SetProperty(ref _ActionLog, value);
        }
        private int _TranslateTimes ;

        public int TranslateTimes
        {
            get => _TranslateTimes;
            set => SetProperty(ref _TranslateTimes, value);
        }

        private string _SubtitleFile2;
        private string curLanguage = null;

        public string SubtitleFile2
        {
            get => _SubtitleFile2;
            set => SetProperty(ref _SubtitleFile2, value);
        }
        private GoogleTranslateLanguage[] multLanguages = new GoogleTranslateLanguage[]
        {
            GoogleTranslateLanguage.zh,
            GoogleTranslateLanguage.en,
            GoogleTranslateLanguage.de,
            GoogleTranslateLanguage.ja,
            GoogleTranslateLanguage.fr,
            GoogleTranslateLanguage.ko,
            GoogleTranslateLanguage.ru,
            GoogleTranslateLanguage.it,
            GoogleTranslateLanguage.ar,
            GoogleTranslateLanguage.es,
            GoogleTranslateLanguage.zh,
        };
        private List<Subtitle> subtitles = new List<Subtitle>();
        private List<Subtitle> subtitlesNew = new List<Subtitle>();
        private bool sameToLast = true;
        private bool randomLanguage = true;
        private GoogleTranslateLanguage[] currentLanguages = null;
        List<List<string>> transList = new List<List<string>>();
        private static readonly int PER_REQUEST_SUBTITLE_COUNT = 30;
        private Barrier barrier;

        private ICommand _LanguageChangedCommand;
        private ICommand _ChangeTypeCommand;
        private ICommand _ChangeTranslateOptionSameToLastCommand;
        private ICommand _ChangeTranslateOptionRandomCommand;
        private ICommand _ChangedTranslateTimesCommand;
        private ICommand _CheckSubtitleFileCommand;
        private ICommand _OpenSubtitleFileCommand;
        private ICommand _CopyLanguageCommand;
        private ICommand _MergeSubtitleCommand;
        private ICommand _SaveSubtitleCommand;
        private ICommand _TranslateSubtitleCommand;

        public ICommand TranslateSubtitleCommand =>
            _TranslateSubtitleCommand
            ?? (
                _TranslateSubtitleCommand = new RelayCommand<object>(o =>
                {
                    DialogResult dialogResult = System.Windows.Forms.MessageBox.Show(
                        "确定打开了翻墙功能",
                        "需要打开翻墙功能",
                        MessageBoxButtons.YesNo
                    );
                    if (dialogResult == DialogResult.No)
                    {
                        return;
                    }
                    SaveSubtitleEnabled = false;
                    object[] objs = (object[])o;

                    TextEditor te1 = (TextEditor)objs[0];
                    TextEditor te2 = (TextEditor)objs[1];
                    var re = SubtitleUtils.ReadSubtitle(te1);
                    if (re.error != SubTitleError.OK)
                    {
                        return;
                    }
                    subtitles = re.list;
                    if (subtitles == null || subtitles.Count == 0)
                    {
                        return;
                    }
                    subtitlesNew.Clear();
                    foreach (Subtitle subtitle in subtitles)
                    {
                        subtitlesNew.Add(
                            new Subtitle(
                                subtitle.Number,
                                subtitle.StartTime,
                                subtitle.EndTime,
                                subtitle.Text
                            )
                        );
                    }
                    ActionLog = "正在翻译";
                    TranslateSubtitleEnabled = false;
                    //语言必须最后是中文
                    int transCount = TranslateTimes;
                    if (TranslateType == TranslateType.Mult)
                    {
                        //随机多语言
                        List<GoogleTranslateLanguage> langs = new List<GoogleTranslateLanguage>();
                        langs.Add(GoogleTranslateLanguage.zh);
                        if (randomLanguage)
                        { //随机语言
                            string lastRandomTranslate = AppConfig.Instance.LastRandomTranslate;
                            if (sameToLast && !string.IsNullOrEmpty(lastRandomTranslate))
                            {
                                List<string> lngs = JsonConvert.DeserializeObject<List<string>>(
                                    lastRandomTranslate
                                );
                                transCount = AppConfig.Instance.LastRandomTranslateCount;
                                Dictionary<string, GoogleTranslateLanguage> dict =
                                    new Dictionary<string, GoogleTranslateLanguage>();
                                foreach (
                                    GoogleTranslateLanguage lang in Utils.getSortGoogleTranslateLanguages()
                                )
                                {
                                    dict.Add(lang.ToString(), lang);
                                }
                                langs.Clear();
                                foreach (string l in lngs)
                                {
                                    GoogleTranslateLanguage val;
                                    dict.TryGetValue(l, out val);
                                    langs.Add(val);
                                }
                                currentLanguages = langs.ToArray();
                            }
                            else
                            {
                                List<GoogleTranslateLanguage> allLanguages =
                                    new List<GoogleTranslateLanguage>();
                                foreach (
                                    GoogleTranslateLanguage lang in Utils.getSortGoogleTranslateLanguages()
                                )
                                {
                                    if (lang != GoogleTranslateLanguage.zh)
                                    {
                                        allLanguages.Add(lang);
                                    }
                                }
                                Random random = new Random();
                                GoogleTranslateLanguage lastLang = GoogleTranslateLanguage.zh;
                                for (int i = 0; i < transCount - 1; i++)
                                {
                                    int idx = random.Next(0, allLanguages.Count - 1);
                                    GoogleTranslateLanguage lang = allLanguages[idx];
                                    while (lastLang == lang)
                                    {
                                        idx = random.Next(0, allLanguages.Count - 1);
                                        lang = allLanguages[idx];
                                    }
                                    lastLang = lang;
                                    langs.Add(lang);
                                }
                                langs.Add(GoogleTranslateLanguage.zh);
                                currentLanguages = langs.ToArray();
                            }
                            List<string> lngs1 = new List<string>();
                            for (int i = 0; i < currentLanguages.Length; i++)
                            {
                                lngs1.Add(currentLanguages[i].ToString());
                            }
                            AppConfig.Instance.LastRandomTranslate = JsonConvert.SerializeObject(
                                lngs1
                            );
                            AppConfig.Instance.LastRandomTranslateCount = transCount;
                            AppConfig.Instance.Save();
                        }
                        else
                        {
                            for (int i = 0; i < transCount / 10; i++)
                            {
                                for (int j = 1; j < multLanguages.Length - 1; j++)
                                {
                                    langs.Add(multLanguages[j]);
                                }
                            }
                            langs.Add(GoogleTranslateLanguage.zh);
                            currentLanguages = langs.ToArray();
                        }
                    }
                    else if (TranslateType == TranslateType.OnlyOne)
                    {
                        List<GoogleTranslateLanguage> allLanguages =
                            new List<GoogleTranslateLanguage>();
                        foreach (
                            GoogleTranslateLanguage langx in Utils.getSortGoogleTranslateLanguages()
                        )
                        {
                            if (langx != GoogleTranslateLanguage.zh)
                            {
                                allLanguages.Add(langx);
                            }
                        }
                        Random random = new Random();

                        currentLanguages = new GoogleTranslateLanguage[transCount + 1];
                        currentLanguages[0] = GoogleTranslateLanguage.zh;
                        GoogleTranslateLanguage selectLanguage = TranslateLanguage;
                        for (int i = 0; i < currentLanguages.Length; i++)
                        {
                            currentLanguages[i] = selectLanguage;
                            if (i % 2 == 0)
                            {
                                currentLanguages[i] = GoogleTranslateLanguage.zh;
                            }
                        }
                        Console.WriteLine();
                    }
                    else if (TranslateType == TranslateType.ToChinese)
                    {
                        List<GoogleTranslateLanguage> googleTranslateLanguages =
                            Utils.getSortGoogleTranslateLanguages();
                        GoogleTranslateLanguage from = TranslateLanguage;
                        GoogleTranslateLanguage to = GoogleTranslateLanguage.zh;
                        currentLanguages = new GoogleTranslateLanguage[2] { from, to };
                    }
                    else if (TranslateType == TranslateType.Random)
                    {
                        List<GoogleTranslateLanguage> allLanguages =
                            new List<GoogleTranslateLanguage>();
                        foreach (
                            GoogleTranslateLanguage langx in Utils.getSortGoogleTranslateLanguages()
                        )
                        {
                            if (langx != GoogleTranslateLanguage.zh)
                            {
                                allLanguages.Add(langx);
                            }
                        }
                        Random random = new Random();
                        int idx = random.Next(0, allLanguages.Count - 1);

                        currentLanguages = new GoogleTranslateLanguage[transCount + 1];
                        currentLanguages[0] = GoogleTranslateLanguage.zh;
                        GoogleTranslateLanguage selectLanguage = allLanguages[idx];
                        for (int i = 0; i < currentLanguages.Length; i++)
                        {
                            currentLanguages[i] = selectLanguage;
                            if (i % 2 == 0)
                            {
                                currentLanguages[i] = GoogleTranslateLanguage.zh;
                            }
                        }
                    }
        
                    Log.Information("字幕数量 " + subtitles.Count);
                    // 调整字幕时间轴

                    curLanguage = "";
                    for (int i = 0; i < currentLanguages.Length; i++)
                    {
                        curLanguage += currentLanguages[i].Desc() + "->";
                    }
                    curLanguage = curLanguage.Substring(0, curLanguage.Length - 2);
                    Log.Information(curLanguage);
                    List<string> subs = new List<string>();
                    transList.Clear();
                    int count = 0;
                    int allCount = 0;
                    // 输出调整后的字幕
                    for (int i = 0; i < subtitles.Count; i++)
                    {
                        subs.Add(subtitles[i].Text);
                        count++;
                        allCount++;
                        if (subtitles.Count == allCount)
                        {
                            if (count <= PER_REQUEST_SUBTITLE_COUNT)
                            {
                                transList.Add(subs);
                            }
                        }
                        else
                        {
                            if (count >= PER_REQUEST_SUBTITLE_COUNT)
                            {
                                transList.Add(subs);
                                count = 0;
                                subs = new List<string>();
                            }
                        }
                    }
                    barrier = new Barrier(
                        transList.Count,
                        a =>
                        {
                            Log.Information("翻译完毕，准备组装数据");
                            ActionLog = "翻译完毕，准备组装数据";
                            //this.mainForm.ShowInfoDialog(transDesc);
                            int index = 0;
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < transList.Count; i++)
                            {
                                for (int j = 0; j < transList[i].Count; j++)
                                {
                                    Subtitle subtitle = new Subtitle(
                                        subtitles[index].Number,
                                        subtitles[index].StartTime,
                                        subtitles[index].EndTime,
                                        subtitles[index].Text
                                    );
                                    ;
                                    string t = transList[i][j];
                                    t = t.Replace("？\n", "\n");
                                    t = t.Replace("。\n", "\n");
                                    t = t.Replace("，\n", "\n");
                                    if (MergeDisplay)
                                    {
                                        string text = subtitles[index].Text;
                                        subtitle.Text = text + "\n" + t;
                                    }
                                    else
                                    {
                                        subtitle.Text = t;
                                    }
                                    subtitlesNew[index].Text = t;
                                    sb.AppendLine(subtitle.ToString());
                                    index++;
                                }
                            }
                            te2.Text = sb.ToString();

                            TranslateSubtitleEnabled = true;
                            ActionLog = "";
                            SaveSubtitleEnabled = true;
                        }
                    );
                    //准备翻译字幕
                    for (int i = 0; i < transList.Count; i++)
                    {
                        int taskNo = i;
                        ThreadPool.QueueUserWorkItem(
                            new WaitCallback(state =>
                            {
                                translateSubtitle(taskNo);
                            })
                        );
                    }
                })
            );
        public async void translateSubtitle(int index)
        {
            ActionLog = "";
            ITranslate translate = new TranslateGoogleBatch();
            int count = transList[index].Count;
            for (int i = 0; i < currentLanguages.Length; i++)
            {
                List<string> old = transList[index];
                //Log.Information("开始翻译[总" + index + "的第" + i + "轮]，原数据量" + count + "，当前数据量" + transList[index].Count);

                if (i == currentLanguages.Length - 1)
                {
                    break;
                }
                DateTime now = DateTime.Now;
                transList[index] = translate.TranslateText(transList[index], currentLanguages[i].ToString(), currentLanguages[i + 1].ToString());
                string info = "[" + (index + 1) + "批" + (i + 1) + "轮 " + currentLanguages[i].Desc() + "-->" + currentLanguages[i + 1].Desc() + "]，数据量" + count + "," + (transList[index].Count == count ? "OK" : "问题数据") + ",耗时" + (DateTime.Now.TimeOfDay.TotalMilliseconds - now.TimeOfDay.TotalMilliseconds);
                //Log.Information(info);
                ActionLog = info;
            }
            App.Current.Dispatcher.BeginInvoke(() => { barrier.SignalAndWait(); });
            
        }
        public ICommand SaveSubtitleCommand =>
            _SaveSubtitleCommand
            ?? (
                _SaveSubtitleCommand = new RelayCommand<object>(o =>
                {
                    SaveSubtitleEnabled = false;
                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                    // 设置对话框的属性
                    //saveFileDialog1.InitialDirectory = "D:\\";  // 设置默认文件夹
                    saveFileDialog1.Filter = "字幕文件 (*.srt)|*.srt|字幕文件 (*.*)|*.*"; // 设置文件类型过滤器

                    // 显示保存文件对话框
                    DialogResult result = saveFileDialog1.ShowDialog();

                    // 处理用户的文件保存
                    if (result == DialogResult.OK)
                    {
                        // 获取用户所选文件的路径
                        string selectedFilePath = saveFileDialog1.FileName;
                        StringBuilder sb = new StringBuilder();
                        foreach (Subtitle subtitle in subtitlesNew)
                        {
                            sb.AppendLine(subtitle.ToString());
                        }
                        System.IO.File.AppendAllText(selectedFilePath, sb.ToString());

                        DialogResult dialogResult = System.Windows.Forms.MessageBox.Show(
                            "是否需要同时保持翻译前后合并字幕文件\n旧字幕在前，新字幕在后",
                            "同时保存翻译前后合并字幕文件",
                            MessageBoxButtons.YesNo
                        );

                        if (dialogResult == DialogResult.Yes)
                        {
                            List<Subtitle> mergeList = SubtitleUtils.MergeSubtitle(
                                subtitles,
                                subtitlesNew
                            );
                            string savaPath = selectedFilePath.Replace(".srt", "_merge.srt");
                            using (StreamWriter writer = new StreamWriter(savaPath))
                            {
                                foreach (Subtitle subtitle in mergeList)
                                {
                                    writer.WriteLine(subtitle.Number);
                                    writer.WriteLine(
                                        $"{subtitle.StartTime:hh\\:mm\\:ss\\,fff} --> {subtitle.EndTime:hh\\:mm\\:ss\\,fff}"
                                    );
                                    writer.WriteLine(subtitle.Text);
                                    writer.WriteLine();
                                }
                            }
                        }

                        dialogResult = MessageBox.Show(
                            "是否需要同时保持无时间轴文件",
                            "同时保存无时间轴文件",
                            MessageBoxButtons.YesNo
                        );
                        if (dialogResult == DialogResult.No)
                        {
                            return;
                        }
                        List<string> lines = new List<string>();
                        foreach (Subtitle subtitle in subtitlesNew)
                        {
                            lines.Add(subtitle.Text);
                        }

                        if (lines != null && lines.Count > 0)
                        {
                            string savaPath = selectedFilePath.Replace(".srt", "_notimeline.txt");
                            Console.WriteLine(savaPath);
                            File.WriteAllLines(savaPath, lines);
                        }
                    }
                })
            );
        public ICommand MergeSubtitleCommand =>
            _MergeSubtitleCommand
            ?? (
                _MergeSubtitleCommand = new RelayCommand<object>(o =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "字幕文件(*.srt)|*.srt";
                    openFileDialog.Title = "打开多个翻译后的合并字幕";
                    openFileDialog.Multiselect = true;
                    openFileDialog.RestoreDirectory = true;
                    openFileDialog.FilterIndex = 1;
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string[] fileNames = openFileDialog.FileNames;
                        if (fileNames.Length < 2)
                        {
                            MessageBox.Show("至少要2个文件才能合并");
                            return;
                        }
                        List<List<SubtitleDue>> allSubtitleDuoList = new List<List<SubtitleDue>>();
                        foreach (string f in fileNames)
                        {
                            List<SubtitleDue> subs = SubtitleUtils.readMultSubtitleFile(f);
                            allSubtitleDuoList.Add(subs);
                        }
                        List<Subtitle> resultList = new List<Subtitle>();
                        List<SubtitleDue> subtitle0Dues = allSubtitleDuoList[0];
                        List<string> subTexts = new List<string>();
                        for (int i = 0; i < subtitle0Dues.Count; i++)
                        {
                            string txt = subtitle0Dues[i].Text;
                            txt += "\n" + subtitle0Dues[i].Text1;
                            for (int j = 1; j < allSubtitleDuoList.Count; j++)
                            {
                                txt += "\n" + allSubtitleDuoList[j][i].Text1;
                            }
                            Subtitle subtitle = new Subtitle(
                                subtitle0Dues[i].Number,
                                subtitle0Dues[i].StartTime,
                                subtitle0Dues[i].EndTime,
                                txt
                            );
                            resultList.Add(subtitle);
                        }
                        subTexts = null;

                        SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                        // 设置对话框的属性
                        //saveFileDialog1.InitialDirectory = "D:\\";  // 设置默认文件夹
                        saveFileDialog1.Filter = "字幕文件 (*.srt)|*.srt|字幕文件 (*.*)|*.*"; // 设置文件类型过滤器

                        // 显示保存文件对话框
                        DialogResult result = saveFileDialog1.ShowDialog();

                        // 处理用户的文件保存
                        if (result == DialogResult.OK)
                        {
                            // 获取用户所选文件的路径
                            string selectedFilePath = saveFileDialog1.FileName;
                            StringBuilder sb = new StringBuilder();
                            foreach (Subtitle subtitle in resultList)
                            {
                                sb.AppendLine(subtitle.ToString());
                            }
                            System.IO.File.AppendAllText(selectedFilePath, sb.ToString());
                        }
                        else
                        {
                            return;
                        }
                    }
                })
            );
        public ICommand CopyLanguageCommand =>
            _CopyLanguageCommand
            ?? (
                _CopyLanguageCommand = new RelayCommand<object>(o =>
                {
                    if (curLanguage != null && curLanguage.Length > 0)
                    {
                        Utils.CopyToClipboard(curLanguage, "语言");
                    }
                })
            );
        public ICommand CheckSubtitleFileCommand =>
            _CheckSubtitleFileCommand
            ?? (
                _CheckSubtitleFileCommand = new RelayCommand<object>(o =>
                {
                    TranslateSubtitleEnabled = false;
                    SaveSubtitleEnabled = false;
                    TextEditor te = o as TextEditor;
                    string name = te.Name.Replace("SubtitleEditer", "");

                    bool check = SubtitleUtils.checkSub(te);
                    if (!check)
                    {
                        return;
                    }
                    if (name.Contains("1"))
                    {
                        te.Save(SubtitleFile1);
                    }
                    else
                    {
                        te.Save(SubtitleFile2);
                    }
                    TranslateSubtitleEnabled = true;
                    SaveSubtitleEnabled = true;
                })
            );

        public ICommand OpenSubtitleFileCommand =>
            _OpenSubtitleFileCommand
            ?? (
                _OpenSubtitleFileCommand = new RelayCommand<object>(o =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "字幕文件(*.srt)|*.srt";
                    openFileDialog.RestoreDirectory = true;
                    openFileDialog.FilterIndex = 1;
                    TextEditor te = o as TextEditor;
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        SubtitleFile1 = openFileDialog.FileName;
                        var fileContent = Utils.ReadFile(SubtitleFile1);
                        te.Text = fileContent.content;
                        bool v = SubtitleUtils.checkSub(te);
                        if (v)
                        {
                            te.Save(SubtitleFile1);
                            return;
                        }
                        else
                        {
                            return;
                        }
                    }
                })
            );

        public ICommand ChangeTranslateOptionRandomCommand =>
            _ChangeTranslateOptionRandomCommand
            ?? (
                _ChangeTranslateOptionRandomCommand = new RelayCommand<object>(o =>
                {
                    if (o == null)
                    {
                        return;
                    }
                    object[] objs = (object[])o;
                    System.Windows.Controls.CheckBox randomCheckBox =
                        (System.Windows.Controls.CheckBox)objs[0];
                    System.Windows.Controls.CheckBox sameToLastCheckBox =
                        (System.Windows.Controls.CheckBox)objs[1];
                    SameToLastTranslateOptionVisibility = Visibility.Hidden;
                    randomLanguage = false;
                    if ((bool)randomCheckBox.IsChecked)
                    {
                        randomLanguage = true;
                        SameToLastTranslateOptionVisibility = Visibility.Visible;
                    }
                    return;
                })
            );
        public ICommand ChangeTranslateOptionSameToLastCommand =>
            _ChangeTranslateOptionSameToLastCommand
            ?? (
                _ChangeTranslateOptionSameToLastCommand = new RelayCommand<object>(o =>
                {
                    if (o == null)
                    {
                        return;
                        //点了  同上次语言
                    }
                    System.Windows.Controls.CheckBox sameToLastCheckBox =
                        (System.Windows.Controls.CheckBox)o;
                    sameToLast = false;
                    if ((bool)sameToLastCheckBox.IsChecked)
                    {
                        sameToLast = true;
                    }
                })
            );

        public ICommand LanguageChangedCommand =>
            _LanguageChangedCommand
            ?? (
                _LanguageChangedCommand = new RelayCommand<object>(o =>
                {
                    if (o == null)
                        return;
                    TranslateLanguage = (GoogleTranslateLanguage)o;
                })
            );
        public ICommand ChangedTranslateTimesCommand =>
            _ChangedTranslateTimesCommand
            ?? (
                _ChangedTranslateTimesCommand = new RelayCommand<object>(o =>
                {
                    if (o == null)
                        return;
                    TranslateTimes = (int)o;
                })
            );

        public ICommand ChangeTypeCommand =>
            _ChangeTypeCommand
            ?? (
                _ChangeTypeCommand = new RelayCommand<object>(o =>
                {
                    if (o == null)
                        return;
                    TranslateType = (TranslateType)o;
                    switch (TranslateType)
                    {
                        case TranslateType.Mult:
                            TranslateOptionsDisplyWidth = Option_Width;
                            TranslateTimesDisplyWidth = Option_Width;
                            LanguageDisplyWidth = 0;
                            break;
                        case TranslateType.OnlyOne:
                            TranslateOptionsDisplyWidth = 0;
                            TranslateTimesDisplyWidth = Option_Width;
                            LanguageDisplyWidth = Option_Width;
                            LanguageText = Language_Middle_Text;
                            break;
                        case TranslateType.ToChinese:
                            TranslateOptionsDisplyWidth = 0;
                            TranslateTimesDisplyWidth = 0;
                            LanguageDisplyWidth = Option_Width;
                            LanguageText = Language_Original_Text;
                            break;
                        case TranslateType.Random:
                            TranslateOptionsDisplyWidth = 0;
                            TranslateTimesDisplyWidth = Option_Width;
                            LanguageDisplyWidth = 0;
                            break;
                    }
                })
            );
    }
}
